﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using Bewise.SmartIndexManager.UI.Forms;
using Microsoft.DataTransformationServices.Controls;
using Bewise.SmartIndexManager.Core;
using Bewise.SmartIndexManager.Core.Classes.Options;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Runtime.Design;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using ConnectionManager = Microsoft.SqlServer.Dts.Runtime.ConnectionManager;
using Bewise.SmartIndexManager.Core.Classes.Types;
using System.Diagnostics;
using System.Text;

namespace Bewise.SmartIndexManager.UI.UserControls
{
    public partial class UcOptions : UserControl, IDTSTaskUIView
    {
        private SmartIndexManager _indexManager;
        private TaskInfosContainer _taskInfosContainer;
        private IDtsConnectionService _connectionsAdodotnet;
        private string _connectionManagerName;

        public UcOptions()
        {
            InitializeComponent();
            comboBoxConnections.SelectedIndexChanged += ComboBoxConnectionsesSelectedIndexChanged;
        }

        #region IDTSTaskUIView Members

public void OnCommit(object taskHost)
{
    if (_taskInfosContainer != null)
    {
        // récupération de toute la configuration de la task dans la propriété TaskInfos
        _indexManager.TaskInfos = Tools.Serialize(_taskInfosContainer);
    }

    if (!string.IsNullOrEmpty(_connectionManagerName))
    {
        // récupération du nom du connectionManager selectionné
        _indexManager.SqlServerConnection = _connectionManagerName;
    }
}

        public void OnInitialize(IDTSTaskUIHost treeHost, TreeNode viewNode, object taskHost, object connections)
        {
            // récupération des ConnectionManagers
            _connectionsAdodotnet = connections as IDtsConnectionService;

            if (taskHost != null)
                if (taskHost is TaskHost)
                {
                    _indexManager = ((TaskHost)taskHost).InnerObject as SmartIndexManager;
                    if (_indexManager != null)
                    {
                        if (string.IsNullOrEmpty(_indexManager.TaskInfos))
                        {
                            _taskInfosContainer = new TaskInfosContainer();
                            _taskInfosContainer.InitOptions();
                        }
                        else
                        {
                            _taskInfosContainer = Tools.Deserialize(_indexManager.TaskInfos);
                        }

                        // bind ComboConnections
                        InitComboBoxConnections();
                        InitComboInitialCatalog();
                    }
                }

            // récupération de l'objet Option de type RequiredMinimumDatabaseOption
            var databaseSizeMinimum = _taskInfosContainer.Options.OfType<RequiredMinimumDatabaseOption>().FirstOrDefault();
            if (numericUpDownDatabaseSizeMinimum != null)
                numericUpDownDatabaseSizeMinimum.DataBindings.Add("Text", databaseSizeMinimum, "MinimumDatabaseSize");

            // récupération de l'objet Option de type RequiredMinimumIndexOption
            var indexSizeMinimum = _taskInfosContainer.Options.OfType<RequiredMinimumIndexOption>().FirstOrDefault();
            if (numericUpDownIndexSizeMinimum != null)
                numericUpDownIndexSizeMinimum.DataBindings.Add("Text", indexSizeMinimum, "MinimumIndexSize");

            // récupération de l'objet Option de type SeuilIndexOption
            var seuilFragmentation = _taskInfosContainer.Options.OfType<SeuilIndexOption>().FirstOrDefault();
            if (numericUpDownSeuilFragmentation != null)
                numericUpDownSeuilFragmentation.DataBindings.Add("Text", seuilFragmentation, "IndexSeuilFragmentation");

            // récupération valeur Log Enabled
            checkBoxOnInformationLog.DataBindings.Add("Checked", _taskInfosContainer, "LogOnInformationIsEnabled");
        }

        // méthode appelée à chaque fois que l'instance sélectionnée change
        void ComboBoxConnectionsesSelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxConnections.SelectedItem != null)
            {
                _connectionManagerName = comboBoxConnections.SelectedItem.ToString();
                // récupération d'un reference vers le "nouveau" ConnectionManager dont le nom est contenu dans comboBoxConnections
                var newConnectionManager = Tools.GetConnectioManager(_connectionsAdodotnet.GetConnections(), comboBoxConnections.SelectedItem.ToString());
                if (newConnectionManager != null)
                    _taskInfosContainer.ConnectionString = newConnectionManager.ConnectionString;
            }
        }

        //private void InitComboInitialCatalog(Microsoft.SqlServer.Dts.Runtime.ConnectionManager currentConnectionManager)
        private void InitComboInitialCatalog()
        {
            this.comboBoxInitialCatalog.DataBindings.Add("SelectedItem", _taskInfosContainer, "SelectedDatabases");
            this.comboBoxInitialCatalog.DataSource = Enum.GetValues(typeof(DatabasesTypeEnum));
        }

        private void InitComboBoxConnections()
        {
            // récupération des ConnectionManagers associés à ADO.NET
            var listAdonetcm = Tools.GetListADO_NETProviders(_connectionsAdodotnet);

            // stockage des ConnectionManagers dans la combo comboBoxConnections
            foreach (var item in listAdonetcm)
                comboBoxConnections.Items.Add(item);

            // Affichage dans la combo comboBoxConnections de l'item SqlServerConnection
            _connectionManagerName = _indexManager.SqlServerConnection;
            if (listAdonetcm.IndexOf(_connectionManagerName) != -1)
                comboBoxConnections.SelectedItem = _connectionManagerName;
        }

        public void OnLoseSelection(ref bool bCanLeaveView, ref string reason)
        {
        }

        public void OnSelection()
        {
        }

        public void OnValidate(ref bool bViewIsValid, ref string reason)
        {
            bViewIsValid = true;

            var sb = new StringBuilder();

            if (string.IsNullOrEmpty(_connectionManagerName) || comboBoxConnections.SelectedItem == null)
            {
                bViewIsValid = false;
                sb.AppendLine("ConnectionString is null. Please select a ConnectionManager");
            }

            reason = sb.ToString();
        }

        #endregion

        private void ButtonNewConnectionClick(object sender, EventArgs e)
        {
            try
            {
                // création Connection Manager _connectionsAdodotnet de type IDtsConnectionService
                var al = this._connectionsAdodotnet.CreateConnection("ADO.NET:SQL");
                ConnectionManager newCM = al[0] as ConnectionManager;

                this.comboBoxConnections.Items.Add(newCM.Name);
                this.comboBoxConnections.SelectedItem = newCM.Name;
                this._connectionsAdodotnet.AddConnectionToPackage(al[0] as ConnectionManager);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " " + ex.Source);
                throw;
            }
        }

        private void ComboBoxDatabasesClick(object sender, EventArgs e)
        {
            // ouverture du formulaire des Bases de données à sélectionner
            using (var formSelectionObject = new SelectObjectForm())
            {
                formSelectionObject.ParentObjectContainer = this._taskInfosContainer;
                formSelectionObject.ShowDialog();
            }
        }
    }
}